{extend name="/base/base" /}
{block name="css"}
    <link rel="stylesheet" href="/static/dream/lib/layui-extend/formSelects/formSelects-v4.css">
{/block}
{block name="global"}

{/block}
{block name="content"}
    <form class="layui-form layui-form-pane" enctype="multipart/form-data" >
        <div class="layui-form-item">
            <label class="layui-form-label">标题</label>
            <div class="layui-input-block">
                <input type="text" name="title" required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">所属栏目</label>
            <div class="layui-input-block">
                <select name="sort_id" xm-select="sort" xm-select-radio xm-select-search="">
                    <option value="">所属栏目</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">标签</label>
            <div class="layui-input-block">
                <select name="tags" xm-select="tags" xm-select-create xm-select-search-type="dl" xm-select-max="5" xm-select-search="">
                    <option value="">请选择所要添加的标签 -- 最多选择5个</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">文章内容</label>
            <div class="layui-input-block">
                <div class="content" name="content"></div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="pull-right">
                <button class="layui-btn" lay-submit lay-filter="submit">立即提交</button>
                <button onclick="window.history.back(-1);" class="layui-btn layui-btn-primary">返回</button>
            </div>
        </div>
    </form>
{/block}

{block name="js"}
    <script src="/static/dream/lib/layui-extend/laymd/marked.min.js"></script>
    <script>
        layui.config({base: '/static/dream/lib/layui-extend/'})
            .extend({'laymd':'laymd/laymd','formSelects':'formSelects/formSelects-v4'})
            .use(['laymd', 'jquery', 'form', 'formSelects', 'layer'], function() {
                var laymd = layui.laymd,
                    $ = layui.jquery,
                    form = layui.form,
                    formSelects = layui.formSelects,
                    layer = layui.layer;


                // 默认方式提交数据
                var fillConfig = {
                    id: 'form',
                    url: "/admin/article/detail/id/"+$getPm.id,
                    type: 'POST',
                    data: {},
                    extraPm: {'id':'hidden'},
                };
                var fill = $.ajax({
                    url: fillConfig.url,
                    type: fillConfig.type?fillConfig.type:"POST",
                    contentType: "application/json;charset=utf-8",
                    data: fillConfig.data?fillConfig.data:{},
                    dataType:"json",
                    // async:false, // 注释后是异步请求，所以要注意这个执行的时间可能在后面代码执行之前
                    success:function(data) {
                        if (data.status == 'fail') {
                            //layer.mag('填充数据有误!',{time:5000});
                            layer.msg('填充数据有误！<span name="count" style="color: red;">3</span>秒后跳转', {
                                icon: 2,
                                success: function (layero, index) {
                                    var countElem = layero.find('span[name="count"]');
                                    var timer = setInterval(function () {
                                        var countTemp = parseInt(countElem.text()) - 1;
                                        countTemp === 0 ? clearInterval(timer):countElem.text(countTemp);
                                        }, 1000);
                                    }
                                }, function () {
                                location.href="{:url('table')}";
                            });
                        }
                        var info = data.result;
                        // 填充数据
                        $('[name]').each(function(index, element){
                            var dataName = $(this).attr('name'),
                                tagName = $(this)[0].tagName;
                            switch (tagName.toLowerCase()) {
                                case 'textarea':
                                    $(this).html(info[dataName]);
                                    break;
                                case 'input':
                                case 'select':
                                    $(this).attr('value', info[dataName]);
                                    break;
                            }
                        });
                        // 额外的参数添加
                        $.each(fillConfig.extraPm, function(index, value){
                            switch (value.toLocaleLowerCase()) {
                                case 'hidden':
                                    console.log(index);
                                    $('form').append("<input type='hidden' name='id' value='"+info[index]+"'>");
                                    break;
                            }
                        });

                        // 设置makedown 的值，必须放在这个里面因为异步请求可能较慢
                        // md.setText($("textarea[name='content']").text());
                    },
                   error:function(data) {
                        console.log(data);
                   }
                });

                // ajax 请求完成之后执行
                fill.done(function(result){
                    // console.log(result);
                    // 设置makedown 的值，必须放在这个里面因为异步请求可能较慢
                    md.setText($("textarea[name='content']").text());
                });

                //监听提交 表单
                form.on('submit(submit)', function(data){
                    data.field.content_html = marked(data.field.content);
                    $.ajax({
                        url : "{:url('editHandle')}",
                        type : "POST",
                        // contentType: "application/json;charset=utf-8", // 上传内容的格式
                        data : data.field,
                        dataType : "json", // 返回的数据格式
                        success : function(data) {
                            if (data.status == 'success') {
                                layer.msg(data.msg, {icon: 1});
                                setTimeout(function(){return false}, 5000);
                                location.href="{:url('table')}";
                            } else {
                                layer.msg(data.msg, {icon: 2});
                            }
                        },
                        error:function(data){
                            layer.msg(data.msg, {icon: 2});
                        }
                    });
                    return false;
                });

                // formSelects
                // 启用多选 所有
                formSelects.undisabled();
                formSelects.data('tags', 'server', {
                    url: '/admin/tag/tableHandle?returnStyle=layui',
                    success: function(id, url, searchVal, result){
                        formSelects.value('tags', $("[name='tags']").attr('value').split(','));
                    }
                });

                // 设置选中的值
                // formSelects.render();
                formSelects.maxTips('tag', function(id, vals, val, max){
                    layer.msg('当前多选框最多只允许选择'+max+'个');
                });
                formSelects.data('sort', 'server', {
                    url: '/admin/articleSort/getGradeTree?returnStyle=layui',
                    success: function(id, url, searchVal, result){
                        formSelects.value('sort', $("[name='sort_id']").attr('value').split(','));
                    }
                });

                // makedown
                //实例化编辑器,可以多个实例
                //改用css选择器,去除init冗余
                var md = laymd('.content', {'name':'content'});

                //内容改变事件
                md.on('change', function () {
                    //这里借用marked.js解析效率比HyperDown快,用户可自行找解析器
                    this.setPreview(marked(this.getText()));
                });

                // 设置当前的makedown信息
                // md.setText();

                $('#tijiao').click(function () {
                    console.log(md.getText()); // md 文档
                    console.log(marked(md.getText())); // html 文档
                });
                //初始化数据预览
                // console.log(md.do('change'));

            });
    </script>
{/block}